//
//  NvEditWatemarkVC.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/9/3.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvEditWatemarkVC.h"
#import "NvAlbumViewController.h"
#import "NvBaseNavigationController.h"
#import "MSSysAlertUtil.h"
#import "NvEditWatemarkImageView.h"
#import "NvWatemarkCVCell.h"
#import "NvsTimelineVideoFx.h"

@interface NvEditWatemarkVC ()<NvLiveWindowPanelViewDelegate, NvsStreamingContextDelegate,NvAlbumViewControllerDelegate,NvEditWatemarkImageViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NvEditWatemarkImageView *imageView;       //水印图片
@property (nonatomic, strong) UIImage *currentImage;                    //当前图片
@property (nonatomic, assign) CGSize imageSize;                         //当前图片大小
@property (nonatomic, assign) CGSize imageMinSize;                      //最小图片大小
@property (nonatomic, assign) BOOL isSave;                              //是否保存到timeline
@property (nonatomic, assign) CGFloat proportion;                       //水印对应比例
@property (nonatomic, assign) BOOL editState;                           //是否可以编辑拖动框

@property (nonatomic, strong) UIButton *pngBtn;                         //png图片选择
@property (nonatomic, strong) UIButton *cafBtn;                         //caf图片选择
@property (nonatomic, strong) UIView *pngLine;
@property (nonatomic, strong) UIView *cafLine;

@property (nonatomic, strong) UICollectionView *watemarkCView;
@property (nonatomic, strong) NSMutableArray *pngArray;
@property (nonatomic, strong) NSMutableArray *cafArray;
@property (nonatomic, strong) NSMutableArray *currentArray;

@property (nonatomic, strong) NvWatemarkItem *currentItem;

//-----------------sdk相关----------------//
@property (nonatomic, strong) NvTimelineData *timelineData;             //数据结构
@property (nonatomic, strong) NvWatermarkInfoModel *currentDataModel;   //copy一份新的model，保存起来
@property (nonatomic, strong) NvWatermarkInfoModel *dataModel;          //创建一个新的model
@property (nonatomic, strong) NvsTimelineVideoFx *videoFx;

@property (nonatomic, strong) UIView *line;

@end

@implementation NvEditWatemarkVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [NvTimelineUtils sharedInstance].isVideoFx = YES;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
     [NvTimelineUtils sharedInstance].isVideoFx = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pngArray = [NSMutableArray array];
    self.cafArray = [NSMutableArray array];
    self.currentArray = [NSMutableArray array];
    [self initTimeline];
    self.liveWindowPanel.delegate = self;
    [self configDataSoure];
    [self addSubviews];
    // Do any additional setup after loading the view.
}

#pragma mark 数据配置
- (void)configDataSoure{
    NvWatemarkItem *item = [[NvWatemarkItem alloc]init];
    item.coverString = @"NvEditWatemarButton";
    item.selected = NO;
    item.isCaf = NO;
    item.isCacheImage = NO;
    [self.pngArray addObject:item];
    
    NvWatemarkItem *item1 = [[NvWatemarkItem alloc]init];
    item1.coverString = @"NvEditWatemarkPng";
    item1.selected = NO;
    item1.isCaf = NO;
    item1.isCacheImage = NO;
    [self.pngArray addObject:item1];
    
    NvWatemarkItem *item2 = [[NvWatemarkItem alloc]init];
    item2.coverString = @"NvEditWatemarkCaf";
    item2.selected = NO;
    item2.isCaf = YES;
    item2.isCacheImage = NO;
    [self.cafArray addObject:item2];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *fileArray = [fm contentsOfDirectoryAtPath:WATEMARK_PATH error:nil];
    for (NSString *fileString in fileArray) {
        if ([fileString hasSuffix:@".png"]) {
            if ([fileString containsString:@"NvEditWatemarkPng"]) {
                [self.pngArray removeObject:item1];
            }
            NvWatemarkItem *fileModel = [[NvWatemarkItem alloc]init];
            fileModel.coverString = [fileString stringByReplacingOccurrencesOfString:@".png" withString:@""];
            fileModel.selected = NO;
            fileModel.isCaf = NO;
            fileModel.isCacheImage = YES;
            [self.pngArray addObject:fileModel];
        }
    }
    
    if (self.timelineData.watermarkInfo.isCaf) {
        self.currentArray = self.cafArray;
    }else{
        self.currentArray = self.pngArray;
    }
    
    for (NvWatemarkItem *model in self.currentArray) {
        if ([model.coverString isEqualToString:self.timelineData.watermarkInfo.imageUrl]) {
            model.selected = YES;
            self.currentItem = model;
        }
    }
    
    if (self.timelineData.watermarkInfo.isCaf) {
        self.currentImage = [NvUtils imageWithName:self.currentItem.coverString];
        self.imageSize = CGSizeMake(self.timelineData.watermarkInfo.displayWidth, self.timelineData.watermarkInfo.displayHeight);
        self.videoFx = [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:@"Storyboard"];
        NSString *descString = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><storyboard sceneWidth=\"Swidth\" sceneHeight=\"SHeight\"><track source=\"cafFile\" width=\"Nwidth\" height=\"Nheight\" clipStart=\"0\" clipDuration=\"2000\" repeat=\"true\"><effect name=\"transform\"><param name=\"opacity\" value=\"1\"/><param name=\"transX\" value=\"0\"/><param name=\"transY\" value=\"0\"/></effect></track></storyboard>"];
        
        descString = [descString stringByReplacingOccurrencesOfString:@"Swidth" withString:[NSString stringWithFormat:@"%d",(int)self.timelineData.watermarkInfo.sceneWidth]];
        descString = [descString stringByReplacingOccurrencesOfString:@"SHeight" withString:[NSString stringWithFormat:@"%d",(int)self.timelineData.watermarkInfo.sceneHeight]];
        descString = [descString stringByReplacingOccurrencesOfString:@"Nwidth" withString:[NSString stringWithFormat:@"%d",(int)self.timelineData.watermarkInfo.displayWidth]];
        descString = [descString stringByReplacingOccurrencesOfString:@"Nheight" withString:[NSString stringWithFormat:@"%d",(int)self.timelineData.watermarkInfo.displayHeight]];
        descString = [descString stringByReplacingOccurrencesOfString:@"cafFile" withString:[NSString stringWithFormat:@"%@.caf",self.timelineData.watermarkInfo.imageUrl]];
        NSLog(@"descString==%@",descString);
        [self.videoFx setStringVal:@"Resource Dir" val:WATEMARK_PATH];
        [self.videoFx setStringVal:@"Description String" val:descString];
        [self.videoFx setBooleanVal:@"Is Animated Sticker" val:true];
        [self.videoFx setFloatVal:@"Sticker TransX" val:self.timelineData.watermarkInfo.marginX];
        [self.videoFx setFloatVal:@"Sticker TransY" val:self.timelineData.watermarkInfo.marginY];
    }
}

#pragma mark 重新创建timeline和数据结构
- (void)initTimeline {
    self.timeline = [NvTimelineUtils createTimeline:self.editMode];
    [NvTimelineUtils recreateTimeline:self.timeline];
    self.proportion = self.timeline.videoRes.imageWidth/ self.liveWindowPanel.liveWindow.width;
    self.timelineData = [NvTimelineData sharedInstance];
    if (self.timelineData.watermarkInfo.imageUrl) {
        self.editState = YES;
        [self.timeline deleteWatermark];
        self.currentImage = [self getImage];
        if (self.timelineData.watermarkInfo.isCaf) {
            self.imageView = [[NvEditWatemarkImageView alloc]initWithFrame:CGRectMake(self.timelineData.watermarkInfo.marginX + self.liveWindowPanel.liveWindow.width/2.0 - self.timelineData.watermarkInfo.displayWidth/2.0,-self.timelineData.watermarkInfo.marginY + self.liveWindowPanel.liveWindow.height/2.0 - self.timelineData.watermarkInfo.displayHeight/2.0,self.timelineData.watermarkInfo.displayWidth,self.timelineData.watermarkInfo.displayHeight)];
        }else{
            self.imageView = [[NvEditWatemarkImageView alloc]initWithFrame:CGRectMake(self.liveWindowPanel.liveWindow.width - self.timelineData.watermarkInfo.marginX / self.proportion - self.timelineData.watermarkInfo.displayWidth / self.proportion,self.timelineData.watermarkInfo.marginY / self.proportion,self.timelineData.watermarkInfo.displayWidth / self.proportion,self.timelineData.watermarkInfo.displayHeight / self.proportion)];
        }
        self.imageView.delegate = self;
        self.imageView.image = self.currentImage;
        [self.liveWindowPanel.liveWindow addSubview:self.imageView];
    }
}

#pragma mark 添加子视图
- (void)addSubviews{
    
    self.pngBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.pngBtn setTitle:@"静态" forState:UIControlStateNormal];
    [self.pngBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#909293"] forState:UIControlStateNormal];
    [self.pngBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#4A90E2"] forState:UIControlStateSelected];
    [self.pngBtn addTarget:self action:@selector(pngBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.pngBtn.titleLabel.font = [UIFont systemFontOfSize:15 * SCREANSCALE];
    [self.view addSubview:self.pngBtn];
    [self.pngBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.liveWindowPanel.mas_bottom);
        make.left.equalTo(self.view);
        make.width.offset(55 * SCREANSCALE);
        make.height.offset(40 * SCREANSCALE);
    }];

    self.cafBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cafBtn setTitle:@"动态" forState:UIControlStateNormal];
    self.cafBtn.titleLabel.font = [UIFont systemFontOfSize:15 * SCREANSCALE];
    [self.cafBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#909293"] forState:UIControlStateNormal];
    [self.cafBtn setTitleColor:[UIColor nv_colorWithHexRGB:@"#4A90E2"] forState:UIControlStateSelected];
    [self.cafBtn addTarget:self action:@selector(cafBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cafBtn];
    [self.cafBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.liveWindowPanel.mas_bottom);
        make.left.equalTo(self.pngBtn.mas_right);
        make.width.offset(55 * SCREANSCALE);
        make.height.offset(40 * SCREANSCALE);
    }];

    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#979797"];
    [self.view addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pngBtn.mas_bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(1);
    }];

    self.pngLine = [[UIView alloc]init];
    self.pngLine.backgroundColor = [UIColor nv_colorWithHexRGB:@"#4A90E2"];
    [lineView addSubview:self.pngLine];
    [self.pngLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pngBtn.mas_bottom);
        make.left.equalTo(self.view);
        make.width.offset(55 * SCREANSCALE);
        make.height.offset(1);
    }];

    self.cafLine = [[UIView alloc]init];
    self.cafLine.backgroundColor = [UIColor nv_colorWithHexRGB:@"#4A90E2"];
    [lineView addSubview:self.cafLine];
    [self.cafLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pngBtn.mas_bottom);
        make.left.equalTo(self.pngLine.mas_right);
        make.width.offset(55 * SCREANSCALE);
        make.height.offset(1);
    }];
    
    if (self.timelineData.watermarkInfo.isCaf) {
        self.cafBtn.selected = YES;
        self.cafLine.hidden = NO;
        self.pngLine.hidden = YES;
    }else{
        self.pngBtn.selected = YES;
        self.pngLine.hidden = NO;
        self.cafLine.hidden = YES;
    }
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(64 * SCREANSCALE, 64*SCREANSCALE);
    layout.minimumLineSpacing = 23 * SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 13 * SCREANSCALE, 0, 0);
    self.watemarkCView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _watemarkCView.backgroundColor = UIColor.clearColor;
    _watemarkCView.delegate = self;
    _watemarkCView.dataSource = self;
    _watemarkCView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_watemarkCView];
    [_watemarkCView registerClass:[NvWatemarkCVCell class] forCellWithReuseIdentifier:@"NvWatemarkCVCell"];
    [_watemarkCView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView.mas_bottom).offset(30 * SCREANSCALE);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.offset(64 * SCREANSCALE);
    }];
    
    UIButton *finshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finshBtn setImage:[NvUtils imageWithName:@"Nvcheck - material"] forState:UIControlStateNormal];
    [finshBtn addTarget:self action:@selector(finshBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:finshBtn];

    [finshBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        if (KIsiPhoneX) {
            make.bottom.equalTo(self.view).offset(-39 * SCREANSCALE);
        }else{
            make.bottom.equalTo(self.view).offset(-15 * SCREANSCALE);
        }
        make.centerX.equalTo(self.view.mas_centerX);
    }];
    
    self.line = [UIView new];
    self.line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@1);
        make.bottom.equalTo(finshBtn.mas_top).offset(-12*SCREANSCALE);
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.currentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NvWatemarkCVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvWatemarkCVCell" forIndexPath:indexPath];
    [cell renderCellWithItem:_currentArray[indexPath.item]];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    for (NvWatemarkItem *model in self.currentArray) {
        model.selected = NO;
    }
    [self seekTimeline];
    NvWatemarkItem *item = self.currentArray[indexPath.item];
    if ([self.currentArray isEqualToArray:self.pngArray]) {
        if (indexPath.item == 0) {
            item.selected = NO;
            [self addBtnClick];
            
        }else{
            item.selected = YES;
            if(![item isEqual:self.currentItem]){
                self.currentItem = item;
                if (item.isCacheImage) {
                    self.currentImage = [UIImage imageWithContentsOfFile:[WATEMARK_PATH stringByAppendingPathComponent:[item.coverString stringByAppendingString:@".png"]]];
                }else{
                    self.currentImage = [NvUtils imageWithName:item.coverString];
                }
                [self adapterWidthAndHeight];
                [self addWatermark];
                self.isSave = YES;
            }
        }
        if (self.videoFx) {
            [self.timeline removeTimelineVideoFx:self.videoFx];
            self.videoFx = nil;
        }
    }else{
        item.selected = YES;
        if (![item isEqual:self.currentItem]) {
            self.currentItem = item;
            if (!self.videoFx) {
                self.videoFx = [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:@"Storyboard"];
            }
             self.currentImage = [NvUtils imageWithName:item.coverString];
            [self adapterWidthAndHeight];
            [self addWatermark];
            self.isSave = YES;
            NSString *descString = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><storyboard sceneWidth=\"Swidth\" sceneHeight=\"SHeight\"><track source=\"cafFile\" width=\"Nwidth\" height=\"Nheight\" clipStart=\"0\" clipDuration=\"2000\" repeat=\"true\"><effect name=\"transform\"><param name=\"opacity\" value=\"1\"/><param name=\"transX\" value=\"0\"/><param name=\"transY\" value=\"0\"/></effect></track></storyboard>"];
            
            descString = [descString stringByReplacingOccurrencesOfString:@"Swidth" withString:[NSString stringWithFormat:@"%d",(int)self.liveWindowPanel.liveWindow.width]];
            descString = [descString stringByReplacingOccurrencesOfString:@"SHeight" withString:[NSString stringWithFormat:@"%d",(int)self.liveWindowPanel.liveWindow.height]];
            descString = [descString stringByReplacingOccurrencesOfString:@"Nwidth" withString:[NSString stringWithFormat:@"%d",(int)self.imageView.width]];
            descString = [descString stringByReplacingOccurrencesOfString:@"Nheight" withString:[NSString stringWithFormat:@"%d",(int)self.imageView.height]];
            descString = [descString stringByReplacingOccurrencesOfString:@"cafFile" withString:[NSString stringWithFormat:@"%@.caf",item.coverString]];
            NSString *packagePath = [[NSBundle bundleForClass:[self class]] bundlePath];
            [self.videoFx setStringVal:@"Resource Dir" val:packagePath];
            [self.videoFx setStringVal:@"Description String" val:descString];
            [self.videoFx setBooleanVal:@"Is Animated Sticker" val:true];
            self.dataModel.marginX = self.liveWindowPanel.liveWindow.width/2.0 - self.imageView.width + self.imageView.width/2.0 - 10;
            self.dataModel.marginY = self.liveWindowPanel.liveWindow.height/2.0 - self.imageView.height + self.imageView.height/2.0 - 10;
            [self.videoFx setFloatVal:@"Sticker TransX" val:self.dataModel.marginX];
            [self.videoFx setFloatVal:@"Sticker TransY" val:self.dataModel.marginY];
        }
    }
    [collectionView reloadData];
}

#pragma mark pngBtnClick点击事件
- (void)pngBtnClick:(UIButton *)sender{
    if (!sender.selected) {
        self.currentArray = self.pngArray;
        for (NvWatemarkItem *model in self.currentArray) {
            if (_currentImage) {
                if ([self.currentItem isEqual:model]) {
                    model.selected = YES;
                }else{
                    model.selected = NO;
                }
            }else{
                model.selected = NO;
            }
        }
        sender.selected = YES;
        self.pngLine.hidden = NO;
        self.cafLine.hidden = YES;
        self.cafBtn.selected = NO;
        [self.watemarkCView reloadData];
    }
}

- (void)cafBtnClick:(UIButton *)sender{
    if (!sender.selected) {
        self.currentArray = self.cafArray;
        for (NvWatemarkItem *model in self.currentArray) {
            if (_currentImage) {
                if ([self.currentItem isEqual:model]) {
                    model.selected = YES;
                }else{
                    model.selected = NO;
                }
            }else{
                model.selected = NO;
            }
        }
        sender.selected = YES;
        self.cafLine.hidden = NO;
        self.pngLine.hidden = YES;
        self.pngBtn.selected = NO;
        [self.watemarkCView reloadData];
    }
}

#pragma mark 添加按钮事件
- (void)addBtnClick{
    [self seekTimeline];
    NvAlbumViewController *album = [NvAlbumViewController new];
    album.delegate = self;
    album.isOnlyImage = YES;
    album.mutableSelect = NO;
    [album customSelectAssetButtonText:@"下一步"];
    NvBaseNavigationController *nav = [[NvBaseNavigationController alloc] initWithRootViewController:album];
    [self presentViewController:nav animated:YES completion:NULL];
}

#pragma mark NvAlbumViewControllerDelegate
- (void)nvAlbumViewController:(NvAlbumViewController *)albumViewController selectAlbumAssets:(NSMutableArray<NvAlbumAsset *> *)assets{
    [albumViewController dismissViewControllerAnimated:YES completion:NULL];
    NvAlbumAsset *asset = [assets firstObject];
    __block BOOL isshowToast = false;
    __weak typeof(self)weakSelf = self;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
    requestOptions.resizeMode   = PHImageRequestOptionsResizeModeExact;
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    requestOptions.synchronous = YES;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset.asset
                                               targetSize:CGSizeMake(self.liveWindowPanel.liveWindow.width,self.liveWindowPanel.liveWindow.height)
                                              contentMode:PHImageContentModeAspectFit
                                                  options:requestOptions
                                            resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                BOOL isIcloud =  [[info valueForKeyPath:@"PHImageResultIsInCloudKey"] boolValue];
                                                if (isIcloud) {
                                                    isshowToast = YES;
                                                } else {
                                                    weakSelf.currentImage = result;
                                                    [weakSelf adapterWidthAndHeight];
                                                    [weakSelf addWatermark];
                                                    weakSelf.isSave = YES;
                                                    NvWatemarkItem *item = [NvWatemarkItem new];
                                                    weakSelf.currentItem = item;
                                                    item.isCaf = NO;
                                                    item.isCacheImage = YES;
                                                    item.selected = YES;
                                                    item.coverString = [NvUtils currentDateAndTime];
                                                    item.coverString = [weakSelf saveImage:result];
                                                    [weakSelf.pngArray insertObject:item atIndex:weakSelf.pngArray.count - 1];
                                                }
                                                dispatch_semaphore_signal(semaphore);
                                            }
     ];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (isshowToast) {
            [MSSysAlertUtil presentAlertViewWithTitle:@"提示" message:@"所选资源在iCloud中" confirmTitle:@"确定" handler:NULL];
        }
    });
    
    [self.watemarkCView reloadData];
}

- (void)nvAlbumViewControllerCancelClick:(NvAlbumViewController *)albumViewController {
    [albumViewController dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark 添加水印图片
- (void)addWatermark{
    if (self.imageView) {
        [self.imageView removeFromSuperview];
        self.imageView = nil;
    }
    self.imageView = [[NvEditWatemarkImageView alloc]initWithFrame:CGRectMake(self.liveWindowPanel.liveWindow.width - self.imageSize.width - 10, 10, self.imageSize.width, self.imageSize.height)];
    self.dataModel.marginX = 10;
    self.dataModel.marginY = 10;
    self.imageView.delegate = self;
    if (!self.currentItem.isCaf) {
        self.imageView.image = self.currentImage;
    }
    self.editState = YES;
    [self.liveWindowPanel.liveWindow addSubview:self.imageView];
}

#pragma mark NvLiveWindowPanelViewDelegate
- (void)playback{
    self.editState = NO;
    [self.imageView hiddenView:!self.editState];
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline{
    self.editState = YES;
    self.imageView.hidden = NO;
    [self.imageView hiddenView:!self.editState];
}

- (void)didPlaybackTimelinePosition:(NvsTimeline *)timeline position:(int64_t)position{
    self.editState = NO;
    [self.imageView hiddenView:!self.editState];
    if (self.videoFx) {
        self.imageView.hidden = YES;
    }else{
        self.imageView.hidden = NO;
    }
}

#pragma mark nvEditWatemarkImageViewWithDelete
//删除水印
- (void)nvEditWatemarkImageViewWithDeleteClick{
    [self.imageView removeFromSuperview];
    self.imageView = nil;
    self.currentItem = nil;
    self.dataModel.imageUrl = nil;
    self.timelineData.watermarkInfo = nil;
    self.isSave = NO;
    if (self.videoFx) {
        [self.timeline removeTimelineVideoFx:self.videoFx];
        [self seekTimeline];
        self.videoFx = nil;
    }
    for (NvWatemarkItem *model in self.pngArray) {
        model.selected = NO;
    }
    for (NvWatemarkItem *model in self.cafArray) {
        model.selected = NO;
    }
    [self.watemarkCView reloadData];
}

//拖拽移动的位置
- (void)nvEditWatemarkImageView:(NvEditWatemarkImageView *)watemarkView updateRect:(CGRect)rect withState:(BOOL)isEnd{
    if (self.editState) {
        self.isSave = YES;
        self.dataModel.marginX = self.liveWindowPanel.liveWindow.width - rect.size.width - rect.origin.x;
        self.dataModel.marginY = rect.origin.y;
        if (self.videoFx) {
            self.dataModel.marginX = rect.origin.x - self.liveWindowPanel.liveWindow.width/2.0 + rect.size.width/2.0;
            self.dataModel.marginY = -(rect.origin.y - self.liveWindowPanel.liveWindow.height/2.0 + rect.size.height/2.0);
            [self.videoFx setFloatVal:@"Sticker TransX" val:self.dataModel.marginX];
            [self.videoFx setFloatVal:@"Sticker TransY" val:self.dataModel.marginY];
            [self.videoFx setFloatVal:@"Sticker Scale"  val:rect.size.height/self.imageSize.height];
            [self seekTimeline];
        }
        if (isEnd) {
            [self.liveWindowPanel playbackBtnClicked];
        }
    }
}

#pragma mark 为图片展示控件计算合理宽度和高度
- (void)adapterWidthAndHeight{
    CGFloat width,height;
    CGFloat viewWidth = self.liveWindowPanel.liveWindow.width;
    CGFloat viewHeight = self.liveWindowPanel.liveWindow.height;
    CGFloat imageWidth = self.currentImage.size.width;
    CGFloat imageHeight = self.currentImage.size.height;
    NSUInteger widthScale = ceilf(imageWidth / viewWidth);
    NSUInteger heightScale = ceilf(imageHeight / viewHeight);
    if (widthScale == 1 && heightScale == 1) {
        width = imageWidth;
        height = imageHeight;
    } else {
        if (widthScale > heightScale) {
            width = viewWidth;
            height = viewWidth / (imageWidth/imageHeight);
        } else {
            width = viewHeight * (imageWidth/imageHeight);
            height = viewHeight;
        }
    }
    self.imageSize = CGSizeMake(width < 20?width * 4:width/3, height < 20 ? height * 4:height/3);
}

#pragma mark 完成按钮点击事件
- (void)finshBtnClick{
    if (self.isSave) {
        [self configWatermarkInfo];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)configWatermarkInfo{
    if (self.currentItem.isCaf) {
        self.dataModel.isCaf = YES;
        self.dataModel.imageUrl = [self saveCaf:self.currentItem.coverString];
        self.dataModel.displayWidth = self.imageView.width;
        self.dataModel.displayHeight = self.imageView.height;
        self.dataModel.marginX = self.dataModel.marginX;
        self.dataModel.marginY = self.dataModel.marginY;
        self.dataModel.sceneWidth = self.liveWindowPanel.liveWindow.width;
        self.dataModel.sceneHeight = self.liveWindowPanel.liveWindow.height;
    }else{
        if (self.currentItem.isCacheImage) {
            self.dataModel.imageUrl = self.currentItem.coverString;
        }else{
            self.dataModel.imageUrl = [self saveImage:self.currentImage];
        }
        self.dataModel.displayWidth = self.imageView.width * self.proportion;
        self.dataModel.displayHeight = self.imageView.height * self.proportion;
        self.dataModel.marginX = self.dataModel.marginX * self.proportion;
        self.dataModel.marginY = self.dataModel.marginY * self.proportion;
    }
    self.timelineData.watermarkInfo = self.dataModel;
}

#pragma mark 返回按钮
- (UIView *)leftNavigationBarItemView {
    return [UIView new];
}

#pragma mark 保存caf
- (NSString *)saveCaf:(NSString *)cafString {
    NSString *path = [WATEMARK_PATH stringByAppendingPathComponent:[cafString stringByAppendingString:@".caf"]];
    NSString *bundle = [[[NSBundle bundleForClass:self.class] bundlePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",cafString]];
    NSData *data = [NSData dataWithContentsOfFile:bundle];
    if ([data writeToFile:path atomically:YES]) {
        NSLog(@"成功");
    }else{
        NSLog(@"失败");
    }
    return cafString;
}

#pragma mark 保存图片
- (NSString *)saveImage:(UIImage *)image {
    NSString *name = [NvUtils currentDateAndTime];
    if (!self.currentItem.isCacheImage) {
        name = self.currentItem.coverString;
    }
    NSString *path = [WATEMARK_PATH stringByAppendingPathComponent:[name stringByAppendingString:@".png"]];
    NSLog(@"name ==%@   path==%@,image == %@",name,path,image);
    NSData *data = UIImagePNGRepresentation(image);
    if ([data writeToFile:path atomically:YES]) {
        NSLog(@"成功");
    }else{
        NSLog(@"失败");
    }
    return name;
}

#pragma mark 读取图片
- (UIImage *)getImage {
    NSString *path = [WATEMARK_PATH stringByAppendingPathComponent:[self.timelineData.watermarkInfo.imageUrl stringByAppendingString:@".png"]];
    UIImage *img = [UIImage imageWithContentsOfFile:path];
    return img;
}

- (NvWatermarkInfoModel *)dataModel{
    if (!_dataModel)
    {
        _dataModel = [NvWatermarkInfoModel new];
    }
    return _dataModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
